import axios from 'axios';
import { get, post } from '@/utils/uniRequest';

// 创建axios实例
// 优先使用环境变量 VUE_APP_BASE_API
// 如果未定义，则根据 NODE_ENV 提供默认值
let baseURL = process.env.VUE_APP_BASE_API;

if (!baseURL) {
  if (process.env.NODE_ENV === 'production') {
    // 生产环境默认地址
    baseURL = 'http://localhost:8001/api';
    console.log('Production mode: Using default API base URL:', baseURL);
  } else {
    // 开发环境默认地址 (HBuilder 调试基座)
    baseURL = 'http://localhost:8001/api';
    console.log('Development mode: Using default API base URL:', baseURL);
  }
} else {
  console.log('Using API base URL from environment variable:', baseURL);
}

const service = axios.create({
  baseURL: baseURL,
  timeout: 10000, // 10 seconds timeout
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 可以在这里添加token等认证信息
    console.log('Sending request to:', config.baseURL + config.url); // Debug log
    return config;
  },
  error => {
    console.error('请求错误 (Request Interceptor):', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log('Received response:', response.status, response.config.url); // Debug log
    // Return the response directly so the calling code can handle status/data
    return response;
  },
  error => {
    console.error('响应错误 (Response Interceptor):', error);

    // Create a user-friendly message
    let userMessage = '';

    if (error.code === 'ECONNABORTED') {
      userMessage = '网络连接超时，请重试';
    } else if (error.message && (error.message.includes('Network Error') || error.message.includes('ERR_CONNECTION_REFUSED'))) {
      userMessage = '网络连接失败，请重试';
    } else if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      switch (error.response.status) {
        case 404:
          userMessage = '请求的资源未找到 (404)';
          break;
        case 500:
          userMessage = '服务器内部错误 (500)，请联系管理员';
          break;
        default:
          userMessage = error.response.data?.message || `请求失败 (${error.response.status})，请联系管理员`;
      }
    } else if (error.request) {
      // The request was made but no response was received
      // For file:// protocol issues, we can provide a specific message
      if (error.request?.responseURL?.startsWith('file://')) {
        userMessage = '请求配置错误：检测到请求被解析为 file:// 协议。请检查环境变量配置或网络代理设置。';
      } else {
        userMessage = '未收到服务器响应，请检查网络连接或服务器状态';
      }
    } else {
      // Something happened in setting up the request that triggered an Error
      userMessage = '请求配置错误: ' + error.message;
    }

    // Attach the user-friendly message to the error object
    error.userMessage = userMessage;

    return Promise.reject(error);
  }
);

/**
 * 获取作业员信息
 * @param {string} workerId - 作业员ID
 * @returns {Promise} 返回包含 RespBean (data为Worker对象) 的 Promise
 */
export function getWorkerInfo(workerId) {
  return get(`/worker/${workerId}`);
}

/**
 * 保存SMT ROLL信息 (已弃用: 请使用 @/api/roll.js 中的 logRollOperation)
 * @deprecated
 * @param {object} data - SMT ROLL信息
 * @returns {Promise}
 */
export function saveRoll(data) {
  return post('/roll/logOperation', data);
}

export default service;